import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './routers'
import appInfo from '@/stores/config/appInfo'
import { useAppStore } from '@/stores/app'
import NProgress from 'nprogress'

const router = createRouter({
  history: createWebHashHistory(appInfo.routeBase),
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { left: 0, top: 0 }
    }
  }
})
router.beforeEach((to, from, next) => {
  NProgress.start()
  const store = useAppStore()
  if (to.name === 'E404') {
    to.query = { redirect: from.fullPath }
    next()
  } else {
    if (to.meta.requireAuth && !store.user.token) {
      store.loginOut()
      store.setRouteState({})
      store.setTagNavList([])
      next({
        name: 'login'
      })
    } else {
      next()
    }
  }
})
router.afterEach((to) => {
  NProgress.done()
  const store = useAppStore()
  let pageTitle = ''
  if (to.meta.title) {
    pageTitle = ' - ' + store.i18n.global.t(to.meta.title)
  }
  document.title = store.appInfo.appName + pageTitle
})
export default router
